package com.jackchong.widget;

import android.content.Context;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.widget.LinearLayout;
import android.widget.Scroller;

import com.jackchong.utils.DeviceInfo;


/**
 * 作者: jack(黄冲)
 * 邮箱: 907755845@qq.com
 * create on 2018/9/20 9:19
 */

public class SideslipView extends JLinearLayout {

    private static final int CLICK_OFFSET = (int) (30 * DeviceInfo.sAutoScaleX);

    private float mDownX, mDownY, mMoveX, mMoveY, mOffsetX, mOffsetY;
    private ScrollerRunnable mRunnable;
    private VelocityTracker mVelocityTracker;
    private int mChildWidth;
    private boolean isOpen;
    private boolean isEnabled = true;
    public static SideslipView mOldSideslipView;

    private boolean enforceClose;

    public SideslipView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mVelocityTracker = VelocityTracker.obtain();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (getChildCount() > 1){
            measureChild(getChildAt(getChildCount() - 1), widthMeasureSpec, heightMeasureSpec);
            mChildWidth = getChildAt(getChildCount() - 1).getMeasuredWidth();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_UP:
                return checkClick(ev);
        }

        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        if (!isEnabled || enforceClose) return super.onInterceptTouchEvent(ev);

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                down(ev);
                break;
            case MotionEvent.ACTION_MOVE:
                return move(ev);
        }
        return super.onInterceptTouchEvent(ev);
    }

    private boolean checkClick(MotionEvent ev) {
        if (mOffsetX < CLICK_OFFSET && mOffsetY < CLICK_OFFSET && ev.getX() < getWidth() - mChildWidth && getScrollX() == mChildWidth){
            closeMenu();
            return false;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                return move(event);
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                return up(event);
        }
        return true;
    }

    @Override
    public void setEnabled(boolean enabled) {
        isEnabled = enabled;
    }

    public void resetMenu(){
        scrollTo(0, 0);
    }

    public void closeMenu(){
        enforceClose = true;

        if (mRunnable != null){
            if (!mRunnable.isFinished()) {
                mRunnable.cancel();
            }
            mRunnable = null;
        }

        mRunnable = new ScrollerRunnable();
        mRunnable.close();
        post(mRunnable);
    }


    class ScrollerRunnable implements Runnable {

        private Scroller mScroller;


        ScrollerRunnable() {
            mScroller = new Scroller(getContext());
        }

        void cancel(){
            mScroller.forceFinished(true);
        }

        boolean isFinished(){
            return mScroller.isFinished();
        }

        void close(){
            isOpen = false;
            mScroller.startScroll(getScrollX(), 0, -getScrollX(), 0, 300);
        }

        void fling(int velocityX){

            int from = getScrollX();

            int open = mChildWidth - from;
            int close = -from;
            int to = 0;

            if (Math.abs(velocityX) > 800){
                to = velocityX > 0 ? close : open;
            }else if (isOpen && getScrollX() > mChildWidth / 2){
                to = open;
            }else if(isOpen && getScrollX() <= mChildWidth / 2){
                to = close;
            }else if (!isOpen && getScrollX() > mChildWidth / 2){
                to = open;
            }else if (!isOpen && getScrollX() <= mChildWidth / 2){
                to = close;
            }

            isOpen = !isOpen;
            mOldSideslipView = SideslipView.this;
            mScroller.startScroll(from, 0, to, 0, 300);
        }

        @Override
        public void run() {
            if (!mScroller.isFinished() && mScroller.computeScrollOffset()) {
                post(() -> scrollTo(mScroller.getCurrX(), 0));
                postDelayed(this, 10);
            }else {
                if (getScrollX() == 0){
                    SideslipView.mOldSideslipView = null;
                }
                enforceClose = false;
            }
        }
    }


    private void down(MotionEvent event) {
        mDownX = mMoveX = event.getX();
        mDownY = mMoveY = event.getY();
        mOffsetX = mOffsetY = 0;

        mVelocityTracker.clear();
        mVelocityTracker.addMovement(event);
        if (mRunnable != null){
            if (!mRunnable.isFinished()) {
                mRunnable.cancel();
            }
            mRunnable = null;
        }
    }

    private boolean move(MotionEvent event) {

        if (!isEnabled) return false;

        getParent().requestDisallowInterceptTouchEvent(getScrollX() != 0) ;

        mVelocityTracker.addMovement(event);
        float dx = event.getX() - mMoveX;
        float dy = event.getY() - mMoveY;

        mOffsetX += Math.abs(dx);
        mOffsetY += Math.abs(dy);

        mMoveX = event.getX();
        mMoveY = event.getY();

        if (mOffsetX < CLICK_OFFSET){
            return false;
        }

        if (getScrollX() + -dx < mChildWidth && getScrollX() + -dx >= 0){
            scrollBy((int) -dx, 0);
            return true;
        }
        return false;
    }


    private boolean up(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP && mOffsetX < CLICK_OFFSET){
            performClick();
            return true;
        }

        mVelocityTracker.addMovement(event);
        mVelocityTracker.computeCurrentVelocity(1000);
        int xV = (int) mVelocityTracker.getXVelocity();
        mRunnable = new ScrollerRunnable();
        mRunnable.fling(xV);
        post(mRunnable);

        return super.onInterceptTouchEvent(event);
    }
}
